package data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.AutoSiteModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class AutoSiteData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "auto_site_";
	
	private int limit = 20;
	
	private int page = 1;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public AutoSiteData() {
		try {
			ObjectifyService.register(AutoSiteModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<AutoSiteModel> list() {
		ArrayList<AutoSiteModel> sites = new ArrayList<AutoSiteModel>();
		
		int start = (page - 1) * limit;
		Query<AutoSiteModel> q = ofy.query(AutoSiteModel.class).limit(limit).offset(start);
		for (AutoSiteModel site: q) {
			sites.add(site);
		}
		
		return sites;
	}
	
	public ArrayList<AutoSiteModel> getAll() {
		ArrayList<AutoSiteModel> sites = new ArrayList<AutoSiteModel>();
		
		Query<AutoSiteModel> q = ofy.query(AutoSiteModel.class);
		for (AutoSiteModel site: q) {
			sites.add(site);
		}
		
		return sites;
	} 
	
	public void insert(AutoSiteModel site) {
		if (cache != null) {
			cache.put(prefix + site.getUrl(), site);
		}
		ofy.put(site);
	}
	
	public void delete(AutoSiteModel site) {
		if (cache != null && cache.containsKey(prefix + site.getUrl())) {
			cache.remove(prefix + site.getUrl());
		}
		
		ofy.delete(site);
	}
	
	public AutoSiteModel getSite(String url) {
		AutoSiteModel site = new AutoSiteModel();
		if (cache != null && cache.containsKey(prefix + url)) {
			site = (AutoSiteModel) cache.get(prefix + url);
		} else {
			try {
				site = ofy.get(new Key<AutoSiteModel>(AutoSiteModel.class, url));
				cache.put(prefix + url, site);
			} catch (Exception e) {
				site = null;
			}
		}
		return site;
	}
}
